//
//  SoundHandler.m
//  iFly
//
//  Copyright (c) 2014 TeamDifferent. All rights reserved.

//Sound Manager Singleton Class

#import "SoundHandler.h"
@interface SoundHandler () {
    NSMutableArray* playSounds;
}
@end

@implementation SoundHandler

static BOOL isInited = NO;

+(id) sharedSoundPlayer {
    static SoundHandler* soundPlayer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        soundPlayer = [[super alloc] init];
    });
    
    return soundPlayer;
}

- (instancetype)init  {
    
    if (isInited) {
        return self;
    }
    self = [super init];
    
    if (self) {
        playSounds = [NSMutableArray array];
        self.backgroundMusicPlayer=[[AVAudioPlayer alloc] init];
        self.gameAudioPlayer=[[AVAudioPlayer alloc] init];
        isInited = YES;
    }
    return self;
}

-(id)copy {
    return [SoundHandler sharedSoundPlayer];
}

-(id)mutableCopy {
    return [SoundHandler sharedSoundPlayer];
}

+(instancetype)alloc {
    return [SoundHandler sharedSoundPlayer];
}

-(void)playSoundWithName:(NSString *)soundName andType:(NSString *)soundType {

    NSURL* sound=[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:soundName ofType:soundType]];
    AVAudioPlayer* audioPlayer =[[AVAudioPlayer alloc]initWithContentsOfURL:sound error:nil];
    [playSounds addObject:audioPlayer];
    if ([playSounds count] > 10) {
        [playSounds removeObjectAtIndex:0];
    }
    [audioPlayer prepareToPlay];
    [audioPlayer play];

}

-(void)playBackgroundMusicWithURL:(NSString*) URL andExtension:(NSString*) extension {
    NSError *error;
    NSURL * backgroundMusicURL = [[NSBundle mainBundle] URLForResource:URL withExtension:extension];
    self.backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
    self.backgroundMusicPlayer.numberOfLoops = -1;
    [self.backgroundMusicPlayer setVolume:0.3];
    [self.backgroundMusicPlayer play];
    
}

-(void) pauseBackgroundMusic {
    if (!self.backgroundMusicPlayer.isPlaying) {
        return;
    }
    [self.backgroundMusicPlayer pause];
}
// play from paused time
-(void) resumeBackgroundMusic {
    [self.backgroundMusicPlayer prepareToPlay];
    [self.backgroundMusicPlayer play];
}
-(void) stopBackgroundMusic {
    [self.backgroundMusicPlayer stop];
}
    
@end
